﻿using BO.Infrastructure.Config;
using BO.Infrastructure.StaticData;
using BO.ProjectManager;
using CBL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.HtmlControls;


namespace BO.Infrastructure.Utils
{
    public class PresentationUtils
    {
        [Obsolete("Use CBL.ExtensionMethods instead.")]
        public static string UnicodeToKoDau(string s)
        {
            return s.ToKoDau();
            //if (string.IsNullOrEmpty(s))
            //    return s;
            //var retVal = String.Empty;
            //for (var i = 0; i < s.Length; i++)
            //{
            //    var pos = UniChars.IndexOf(s[i].ToString());
            //    if (pos >= 0)
            //        retVal += KoDauChars[pos];
            //    else
            //        retVal += s[i];
            //}
            //return retVal;
        }

        [Obsolete("Use CBL.ExtensionMethods instead.", true)]
        public static string UnicodeToKoDauAndGach(string s)
        {
            return s.ToKoDauAndGach();
            //if (string.IsNullOrEmpty(s))
            //    return s;
            //s = UnicodeToKoDau(s.Trim());
            //return Regex.Replace(s, "[^a-zA-Z0-9]+", "-");
        }

        [Obsolete("Use CBL.CommonBusinessObject instead.")]
        public static string EnCode(string s)
        {
            return CommonBusinessObject.EnCode(s);
        }

        [Obsolete("Use CBL.CommonBusinessObject instead.")]
        public static string EncodeBase64(string s)
        {
            return CommonBusinessObject.EncodeBase64(s);
        }

        [Obsolete("Use CBL.ExtensionMethods instead.")]
        public static string GetCacheKey(string functionName, IEnumerable<object> listParams, string uniqueText = "")
        {
            return CommonBusinessObject.GetCacheKey(functionName, listParams, uniqueText);
        }


        #region Meta data
        public static void AddFacebookMetaData(System.Web.UI.Page page, string type, string url, string title, string image, string description)
        {
            var ogType = new HtmlMeta();

            ogType.Attributes["property"] = "og:type";
            ogType.Content = type;
            page.Header.Controls.Add(ogType);

            var ogUrl = new HtmlMeta();
            ogUrl.Attributes["property"] = "og:url";
            ogUrl.Content = url;
            page.Header.Controls.Add(ogUrl);

            var ogTitle = new HtmlMeta();
            ogTitle.Attributes["property"] = "og:title";
            ogTitle.Content = title;
            page.Header.Controls.Add(ogTitle);

            var ogImage = new HtmlMeta();
            ogImage.Attributes["property"] = "og:image";
            ogImage.Content = image;
            page.Header.Controls.Add(ogImage);


            var ogDesc = new HtmlMeta();
            ogDesc.Attributes["property"] = "og:description";
            ogDesc.Content = description;
            page.Header.Controls.Add(ogDesc);
        }

        public static void AddFacebookVideoMetaData(System.Web.UI.Page page, string url, string title, string image,
            string description, string video, string videoHeight, string videoWidth, string videoVideotag, string videoType)
        {
            var ogUrl = new HtmlMeta();
            ogUrl.Attributes["property"] = "og:url";
            ogUrl.Content = url;
            page.Header.Controls.Add(ogUrl);

            var ogTitle = new HtmlMeta();
            ogTitle.Attributes["property"] = "og:title";
            ogTitle.Content = title;
            page.Header.Controls.Add(ogTitle);

            var ogImage = new HtmlMeta();
            ogImage.Attributes["property"] = "og:image";
            ogImage.Content = image;
            page.Header.Controls.Add(ogImage);

            var ogDescription = new HtmlMeta();
            ogDescription.Attributes["property"] = "og:description";
            ogDescription.Content = description;
            page.Header.Controls.Add(ogDescription);

            var ogVideo = new HtmlMeta();
            ogVideo.Attributes["property"] = "og:video";
            ogVideo.Content = video;
            page.Header.Controls.Add(ogVideo);

            var ogVideoHeight = new HtmlMeta();
            ogVideoHeight.Attributes["property"] = "og:video:height";
            ogVideoHeight.Content = videoHeight;
            page.Header.Controls.Add(ogVideoHeight);

            var ogVideoWidth = new HtmlMeta();
            ogVideoWidth.Attributes["property"] = "og:video:width";
            ogVideoWidth.Content = videoWidth;
            page.Header.Controls.Add(ogVideoWidth);


            var ogVideoTag = new HtmlMeta();
            ogVideoTag.Attributes["property"] = "og:video:videotag";
            ogVideoTag.Content = videoVideotag;
            page.Header.Controls.Add(ogVideoTag);

            var ogVideoType = new HtmlMeta();
            ogVideoType.Attributes["property"] = "og:video:videotype";
            ogVideoType.Content = videoType;
            page.Header.Controls.Add(ogVideoType);
        }

        public static void SetCanonicalLink(System.Web.UI.Page page, string url)
        {
            var canonicalLink = new HtmlLink { Href = url };
            canonicalLink.Attributes["rel"] = "canonical";
            page.Header.Controls.Add(canonicalLink);
        }

        public static void AddBasicMetaData(System.Web.UI.Page page, string pageTitle, string desc, string keywords = "")
        {

            var metaDesc = new HtmlMeta { Name = "description", Content = desc };
            page.Header.Controls.AddAt(1, metaDesc);

            var metaNewsKeywords = new HtmlMeta { Name = "news_keywords", Content = keywords };
            page.Header.Controls.AddAt(2, metaNewsKeywords);

            if (!string.IsNullOrEmpty(pageTitle))
            {
                page.Header.Title = pageTitle;
            }

        }

        public static void AddMeta(System.Web.UI.Page page, string strId, string metaName, string content)
        {
            var meta = new HtmlMeta { ID = strId, Name = metaName, Content = content };
            var ctlMeta = (HtmlMeta)page.Header.FindControl(strId);
            if (ctlMeta == null)
            {
                page.Header.Controls.Add(meta);
            }
            else
            {
                ctlMeta.Content = content;
            }
        }
        #endregion

        #region DetailUrl
        public class UrlBuilder
        {
            public static string BuildAbsoluteUrl(string relativeUrl)
            {
                if (!string.IsNullOrEmpty(relativeUrl) && !relativeUrl.StartsWith("http"))
                    //return AppSettings.Domain.TrimEnd('/') + "/" + relativeUrl.TrimStart('/');
                    return "http://soha.vn" + "/" + relativeUrl.TrimStart('/');
                return relativeUrl;
            }

            public static string BuildTagUrl(string tagName, bool mustCallMethodUnicodeToKoDauAndGach = true)
            {
                if (!string.IsNullOrEmpty(tagName))
                {
                    tagName = tagName.ToLower();
                    return string.Format("/{0}.html", mustCallMethodUnicodeToKoDauAndGach ?
                        tagName.ToKoDauAndGach()
                        : tagName);
                }
                return string.Empty;
            }

            public static string BuildCatUrl(string categoryName, bool mustCallMethodUnicodeToKoDauAndGach = true)
            {
                return string.Format(
                        "/{0}{1}",
                        mustCallMethodUnicodeToKoDauAndGach ? categoryName.ToKoDauAndGach().ToLower() : categoryName,
                        AppSettings.UrlExtenstion);
            }

            public static string BuildCatUrl(string categoryName, string parentCategoryName, bool mustCallMethodUnicodeToKoDauAndGach = true)
            {
                return string.Format(
                        "/{0}/{1}{2}",
                        mustCallMethodUnicodeToKoDauAndGach ? categoryName.ToKoDauAndGach().ToLower() : categoryName,
                        mustCallMethodUnicodeToKoDauAndGach ? parentCategoryName.ToKoDauAndGach().ToLower() : parentCategoryName,
                        AppSettings.UrlExtenstion);
            }

            public static string BuildThreadUrl(int threadId, string threadName, bool mustCallMethodUnicodeToKoDauAndGach = true)
            {
                threadName = threadName.ToLower();
                return string.Format("/{0}-e{1}{2}",
                    mustCallMethodUnicodeToKoDauAndGach ? threadName.ToKoDauAndGach() : threadName,
                    threadId,
                    AppSettings.UrlExtenstion);
            }

            public static string BuildPagingUrl(string url, int pageIndex)
            {
                return url.Replace(AppSettings.UrlExtenstion, string.Format("/page-{0}{1}", pageIndex, AppSettings.UrlExtenstion));
            }

            public static object BuildVideoUrl(object name, object id)
            {
                return string.Format("/video-{0}/{1}{2}", id, name.ToString().ToKoDauAndGach().ToLower(), AppSettings.UrlExtenstion);
            }

            public static string BuildZoneVideoUrl(int zoneId, string zoneUrl)
            {
                return string.Format("/videotag-{0}/{1}{2}", zoneId, zoneUrl.ToLower(), AppSettings.UrlExtenstion);
            }
        }
        #endregion



        #region Convert data
        public static T JsonToObject<T>(string jsonString)
        {
            try
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonString);
            }
            catch
            {
                return default(T);
            }
        }

        public static string ObjectToJson(object obj)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
        }

        public static bool Object2Boolean(string value)
        {

            if (string.IsNullOrEmpty(value))
            {
                return default(bool);
            }
            try
            {
                return bool.Parse(value);
            }
            catch
            {
                int i;
                int.TryParse(value, out i);
                return i > 0;
            }
        }

        public static int Object2Integer(string value)
        {
            int n;
            int.TryParse(value, out n);
            return n;
        }

        public static long Object2Long(string value)
        {
            long n;
            long.TryParse(value, out n);
            return n;
        }

        public static DateTime Object2DateTime(string value)
        {
            DateTime result;
            DateTime.TryParse(value, out result);
            return result;
        }
        #endregion

        public class Video
        {
            public static string BuildEmbedCode(string key, string name, int width, int height, string avatar = "", bool autostart = false, int playerIndex = -1, string title = "")
            {
                if (!string.IsNullOrEmpty(title))
                    title = EnCode(title);
                var sb = new StringBuilder();
                string id = playerIndex >= 0 ? string.Format("object_Kenh14_{0}", playerIndex) : "object_Kenh14";
                const string classId = "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
                var videoUrl = string.Format("http://cache.hosting.vcmedia.vn/?key={0}&amp;pname={1}", key, name);
                sb.AppendFormat("<object width=\"{0}\" height=\"{1}\" classid=\"{3}\" id=\"{2}\">", width, height, id, classId);
                sb.Append("<param name=\"wmode\" value=\"transparent\">");
                sb.AppendFormat("<param name=\"movie\" value=\"{0}\">", videoUrl);
                sb.Append("<param name=\"allowFullScreen\" value=\"true\">");
                sb.AppendFormat("<param name=\"flashvars\" value=\"videotag=true&autostart={0}&image={1}{2}\">", autostart, avatar,
                    string.IsNullOrEmpty(title) ? string.Empty : string.Format("&addtitleplugin.enable=true&addtitleplugin.title={0}", title));
                sb.Append("<param name=\"allowscriptaccess\" value=\"always\">");
                sb.Append("<param name=\"bgcolor\" value=\"#000000\">");
                sb.AppendFormat("<embed width=\"{0}\" height=\"{1}\"  src=\"{2}\"  id=\"{3}\" name=\"movie\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" wmode=\"transparent\" flashvars=\"videotag=true&autostart={4}&image={5}{6}\" bgcolor=\"#000000\" quality=\"high\"></object>",
                    width, height, videoUrl, id, autostart, avatar,
                    string.IsNullOrEmpty(title) ? string.Empty : string.Format("&addtitleplugin.enable=true&addtitleplugin.title={0}", title));
                return sb.ToString();
            }
        }

        public static void AddCss(System.Web.UI.Page page, string cssSource, bool usingMasterPageVersion = false, bool isTheme = false)
        {
            var currentStorageSetting = PMBO.GetCurrentStorageConfig();

            if (usingMasterPageVersion && !currentStorageSetting.IsUsed)
            {
                var ltrVersion = page.Header.FindControl("ltrVersion") as System.Web.UI.WebControls.Literal;
                if (ltrVersion != null)
                {
                    var version = Object2Integer(ltrVersion.Text);
                    if (version > 0)
                        cssSource = string.Format("{0}?v={1}", cssSource, version);
                }
            }

            var css = new HtmlLink { Href = cssSource };
            css.Attributes["rel"] = "stylesheet";
            css.Attributes["type"] = "text/css";
            if (isTheme)
            {
                page.Header.Controls.AddAt(page.Header.Controls.Count, css);
            }
            else
                if (cssSource.Contains("/combres.axd") || cssSource.Contains(currentStorageSetting.Domain))

                    page.Header.Controls.AddAt(0, css);
                else
                    page.Header.Controls.Add(css);

        }

        public static void AddJs(System.Web.UI.Page page, string jsSource, string version = "")
        {

            if (!string.IsNullOrEmpty(version))
            {
                jsSource = string.Format("{0}?v={1}", jsSource, version);
            }
            var js = new HtmlGenericControl("script");
            js.Attributes.Add("type", "text/javascript");
            js.Attributes.Add("src", jsSource);
            page.Header.Controls.Add(js);
        }

        public class Photo
        {
            private static readonly string ImageDomain = AppSettings.ImageDomain.TrimEnd('/');
            private static readonly string ImageVideoDomain = AppSettings.ImageVideoDomain.TrimEnd('/');
            public static string GetSourceImage(string imagePath)
            {
                if (!string.IsNullOrEmpty(imagePath) && !imagePath.StartsWith("http"))
                {
                    if (imagePath.StartsWith("http"))
                    {
                        return imagePath;
                    }
                    imagePath = imagePath.TrimStart('/');

                    return string.Format("{0}/{1}", ImageDomain, imagePath);
                }
                return string.Empty;
            }

            public static string GetThumbImage_W(string imagePath, int imageWidth)
            {
                if (!string.IsNullOrEmpty(imagePath))
                {
                    if (imagePath.StartsWith("http"))
                    {
                        return imagePath;
                    }

                    imagePath = imagePath.TrimStart('/');

                    return string.Format("{0}/thumb_w/{1}/{2}", ImageDomain, imageWidth, imagePath);
                }
                return string.Empty;
            }

            public static string GetThumbImage_Zoom(string imagePath, int imageWidth, int imageHeight)
            {
                if (!string.IsNullOrEmpty(imagePath))
                {
                    if (imagePath.StartsWith("http"))
                    {
                        return imagePath;
                    }
                    imagePath = imagePath.TrimStart('/');
                    string format = "{0}/zoom/{1}_{2}/{3}";

                    return string.Format(format, ImageDomain, imageWidth, imageHeight, imagePath);
                }
                return string.Empty;
            }

            public static string VideoThumb_Zoom(string url, int width, int height)
            {

                if (url.StartsWith("http"))
                {
                    if (url.StartsWith(ImageVideoDomain))
                    {
                        url = url.Replace(ImageVideoDomain, string.Empty);
                    }
                    else
                    {
                        return url;
                    }
                }
                return string.Format("{0}/zoom/{1}_{2}/{3}", ImageVideoDomain, width, height, url.TrimStart('/'));
            }

            public static string BuildNewsAvatar(DataRow r, int imageWidth, bool lazyLoad = false)
            {
                return lazyLoad
                ? string.Format(
                    "<a href=\"{0}\" title=\"{1}\"><img title=\"{1}\" alt=\"{1}\" class=\"lazy\" data-original=\"{2}\" width=\"{3}\" src=\"http://soha4.vcmedia.vn/1px.gif\" /><noscript><img title=\"{1}\" alt=\"{1}\" src=\"{2}\" width=\"{3}\" /></noscript></a>",
                    r[SqlConstants.NewsPublish.Url],
                    EnCode(r[SqlConstants.NewsPublish.Title].ToString()),
                    GetThumbImage_W(r[SqlConstants.NewsPublish.Avatar].ToString(), imageWidth),
                    imageWidth
                    )
                    : string.Format(
                    "<a href=\"{0}\" title=\"{1}\"><img title=\"{1}\" alt=\"{1}\" src=\"{2}\" width=\"{3}\" /></a>",
                    r[SqlConstants.NewsPublish.Url],
                    EnCode(r[SqlConstants.NewsPublish.Title].ToString()),
                    GetThumbImage_W(r[SqlConstants.NewsPublish.Avatar].ToString(), imageWidth),
                    imageWidth
                    );
            }

            public static string BuildNewsAvatar(DataRow r, int imageWidth, int imageHeight, bool lazyLoad = false)
            {
                return
                    lazyLoad
                ?
                string.Format(
                    "<a href=\"{0}\" title=\"{1}\"><img title=\"{1}\" alt=\"{1}\" class=\"lazy\" data-original=\"{2}\" width=\"{3}\" height=\"{4}\" src=\"http://soha4.vcmedia.vn/1px.gif\" /><noscript><img title=\"{1}\" alt=\"{1}\" src=\"{2}\" width=\"{3}\" height=\"{4}\" /></noscript></a>",
                    r[SqlConstants.NewsPublish.Url],
                    EnCode(r[SqlConstants.NewsPublish.Title].ToString()),
                    GetThumbImage_Zoom(r[SqlConstants.NewsPublish.Avatar].ToString(), imageWidth, imageHeight),
                    imageWidth,
                    imageHeight
                    ) : string.Format(
                    "<a href=\"{0}\" title=\"{1}\"><img title=\"{1}\" alt=\"{1}\" src=\"{2}\" width=\"{3}\" height=\"{4}\" /></a>",
                    r[SqlConstants.NewsPublish.Url],
                    EnCode(r[SqlConstants.NewsPublish.Title].ToString()),
                    GetThumbImage_Zoom(r[SqlConstants.NewsPublish.Avatar].ToString(), imageWidth, imageHeight),
                    imageWidth,
                    imageHeight
                    );
            }

            public static string BuildPhoto(string source, string title, string href, int width, int height, bool mustThumb = true, bool lazyLoad = false)
            {
                if (mustThumb && width > 0 && !source.StartsWith("http"))
                {
                    source = height > 0 ? GetThumbImage_Zoom(source, width, height) : GetThumbImage_W(source, width);
                }

                return
                  lazyLoad
                ?
                string.Format("<a title=\"{1}\" href=\"{4}\"><img itemprop=\"image\" class=\"lazy\" data-original=\"{0}\" src=\"http://soha4.vcmedia.vn/1px.gif\" title=\"{1}\" alt=\"{1}\" {2} {3}/>" +
                              "<noscript><img itemprop=\"image\" src=\"{0}\" title=\"{1}\" alt=\"{1}\" {2} {3}/></noscript>" +
                              "</a>",
                   source,
                   HttpUtility.HtmlEncode(title),
                   width > 0 ? string.Format("width=\"{0}\"", width) : string.Empty,
                   height > 0 ? string.Format("height=\"{0}\"", height) : string.Empty,
                   href)
                   : string.Format("<a title=\"{1}\" href=\"{4}\"><img itemprop=\"image\" src=\"{0}\" title=\"{1}\" alt=\"{1}\" {2} {3}/></a>",
                   source,
                   HttpUtility.HtmlEncode(title),
                   width > 0 ? string.Format("width=\"{0}\"", width) : string.Empty,
                   height > 0 ? string.Format("height=\"{0}\"", height) : string.Empty,
                   href);
            }

            public static string BuildPhoto(string source, string title, int width, int height, bool mustThumb = true, bool lazyLoad = false)
            {
                if (mustThumb && width > 0 && !source.StartsWith("http"))
                {
                    source = height > 0 ? GetThumbImage_Zoom(source, width, height) : GetThumbImage_W(source, width);
                }
                return
                   lazyLoad
                   ? string.Format("<img class=\"lazy\" data-original=\"{0}\" src=\"http://soha4.vcmedia.vn/1px.gif\" title=\"{1}\" alt=\"{1}\" {2} {3}/><noscript><img src=\"{0}\" title=\"{1}\" alt=\"{1}\" {2} {3}/></noscript>",
                                  source,
                                  HttpUtility.HtmlEncode(title),
                                  width > 0 ? string.Format("width=\"{0}\"", width) : string.Empty,
                                  height > 0 ? string.Format("height=\"{0}\"", height) : string.Empty)

                    : string.Format("<img src=\"{0}\" title=\"{1}\" alt=\"{1}\" {2} {3}/>",
                    source,
                    HttpUtility.HtmlEncode(title),
                    width > 0 ? string.Format("width=\"{0}\"", width) : string.Empty,
                    height > 0 ? string.Format("height=\"{0}\"", height) : string.Empty);
            }

            public static string BuildPhoto(string source, string title, string href)
            {
                return
                    string.Format("<a title=\"{1}\" href=\"{2}\"><img itemprop=\"image\" src=\"{0}\" title=\"{1}\" alt=\"{1}\"/></a>",
                   source,
                   HttpUtility.HtmlEncode(title),
                   href);
            }

            public static string BuildPhoto(string source, string title)
            {
                return
                    string.Format("<img itemprop=\"image\" src=\"{0}\" title=\"{1}\" alt=\"{1}\"/>",
                   source,
                   HttpUtility.HtmlEncode(title));
            }

            public static string GetVideoAvatarSource(string imageUrl)
            {
                if (imageUrl.StartsWith("http"))
                {
                    return imageUrl;
                }
                return ImageVideoDomain + "/" + imageUrl.TrimStart('/');
            }

            public static object BuildVideoAvatar(DataRow r, int imageWidth, int imageHeight)
            {
                return string.Format(
                    "<a href=\"{0}\" title=\"{1}\"><img title=\"{1}\" alt=\"{1}\" src=\"{2}\" width=\"{3}\" height=\"{4}\" /></a>",
                    r[SqlConstants.Video.Url],
                    EnCode(r[SqlConstants.Video.Name].ToString()),
                    VideoThumb_Zoom(r[SqlConstants.Video.Avatar].ToString(), imageWidth, imageHeight),
                    imageWidth,
                    imageHeight
                    );
            }

            public static object BuildVideoAvatar(DataRow r, int imageWidth, int imageHeight, KeyValuePair<string, string>[] attributes)
            {
                var sb = new StringBuilder();

                if (attributes != null && attributes.Any())
                {
                    foreach (var keyValuePair in attributes)
                    {
                        sb.AppendFormat(" {0} = \"{1}\"", keyValuePair.Key, keyValuePair.Value);
                    }
                }
                return string.Format(
                    "<a href=\"{0}\" title=\"{1}\" {5}><img title=\"{1}\" alt=\"{1}\" src=\"{2}\" width=\"{3}\" height=\"{4}\" /></a>",
                    r[SqlConstants.Video.Url],
                    EnCode(r[SqlConstants.Video.Name].ToString()),
                    VideoThumb_Zoom(r[SqlConstants.Video.Avatar].ToString(), imageWidth, imageHeight),
                    imageWidth,
                    imageHeight,
                    sb
                    );
            }
        }

        public class ChannelVN
        {
            /// <summary>
            /// Register các giá trị vào hiddenFields phục vụ cho report trong cms.
            /// </summary>
            /// <param name="page">Trang aspx hiện tại</param>
            /// <param name="newsId">required</param>
            /// <param name="newsTitle">not required, có thể pass vào string.Empty hoặc ""</param>
            /// <param name="catId">required</param>
            /// <param name="catName">not required, có thể pass vào string.Empty hoặc ""</param>
            public static void RegisterReportValues(System.Web.UI.Page page, long newsId, int catId, string newsTitle = "", string catName = "")
            {
                page.ClientScript.RegisterHiddenField("hidReportNewsID", newsId.ToString());
                page.ClientScript.RegisterHiddenField("hidReportNewsTitle", newsTitle);
                page.ClientScript.RegisterHiddenField("hidReportCatID", catId.ToString());
                page.ClientScript.RegisterHiddenField("hidReportCatName", catName);
            }
        }
    }
}
